package com.kssoft.ebd.spider.processor;

import cn.hutool.core.thread.ThreadUtil;
import com.kssoft.ebd.spider.common.CommonUtils;
import com.kssoft.ebd.spider.common.NullCookiesException;
import com.kssoft.ebd.spider.common.PageModelType;
import com.kssoft.ebd.spider.common.config.SpiderConfig;
import com.kssoft.ebd.spider.http.HttpClientUtil;
import com.kssoft.ebd.spider.pool.WebDriverPool;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.io.*;
import java.util.Map;
import java.util.Set;

/**
 * @author liwu
 * @since 2025/6/18
 */
@Component
public class StartBroadcastProcessor implements PageProcessor {

    @Autowired
    private SpiderConfig spiderConfig;
    private Set<Cookie> startBroadcastHomeCookies;
    @Autowired
    private HomeProcessor homeProcessor;
    @Autowired
    private WebDriverPool webDriverPool;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final Site SITE = Site.me().setRetryTimes(3).setSleepTime(100).setTimeOut(3000);

    @Override
    public void process(Page page) {

        //判断是否登录主页
        if (page.getHtml().xpath("//*[@id=\"password\"]").match() || page.getRawText().contains("登录") || page.getRawText().contains("login")) {
            toStartBroadcastHome();
             logger.info("登录开广播成功");
        }

         logger.info("登录开广播cookie 有效");
    }

    @Override
    public Site getSite() {
        try {
            CommonUtils.getCookieToSite(SITE, PageModelType.StartBroadcast, SpiderConfig.START_BROADCAST_COOKIE_FILE_PATH);
        } catch (Exception e) {
            toStartBroadcastHome();
            try {
                CommonUtils.getCookieToSite(SITE, PageModelType.StartBroadcast, SpiderConfig.START_BROADCAST_COOKIE_FILE_PATH);
            } catch (Exception ex) {

            }
        }
        return SITE;
    }

    //使用 selenium 来模拟用户的登录获取cookie信息  跳转到主页
    private WebDriver login(){
        WebDriver driver  = CommonUtils.webDriverHashMap.get(PageModelType.StartBroadcast);
        if (driver == null) {
            driver = webDriverPool.getSigle();
            CommonUtils.webDriverHashMap.put(PageModelType.StartBroadcast, driver);
        }
        driver.get(spiderConfig.getHomePageUrl());
        try {

            WebElement username = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("username")));
            WebElement password = new WebDriverWait(driver, 3).until(browser -> browser.findElement(By.id("password")));

            username.clear();
            username.sendKeys(spiderConfig.getUsername());

            password.clear();
            password.sendKeys(spiderConfig.getPassword() + Keys.ENTER);
        }catch (Exception e){
            logger.error("已登录");
        }
        return driver;
    }
    // 模拟点击菜单跳转到开播主页
    private void toStartBroadcastHome(){
        WebDriver driver   = login();
        logger.info("开始登录开广播"+driver);
        ThreadUtil.sleep(3000);
        driver.get(spiderConfig.getStartBroadcastHomePageUrl());
        ThreadUtil.sleep(3000);
        startBroadcastHomeCookies = driver.manage().getCookies();
        try {
            CommonUtils.saveStartBroadcastCookies(startBroadcastHomeCookies);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取开播主页cookie
     * @return
     */
    public Map<String, String> getStartBroadcastCookies() {
        if(isLogin()){
            try {
                return CommonUtils.getStartBroadcastCookies();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NullCookiesException e) {
                throw new RuntimeException(e);
            }
        }
        start();
        try {
            return CommonUtils.getStartBroadcastCookies();
        } catch (Exception e) {
            e.printStackTrace();
             logger.error("获取开播cookie 失败");
             throw new RuntimeException(e);
        }
    }

    private WebDriver start() {

        Map<String, String> startBroadcastCookies = null;
        try {
            startBroadcastCookies = CommonUtils.getStartBroadcastCookies();
        } catch (Exception e) {
            e.printStackTrace();
             logger.error("获取开播cookie 失败");
        }
        if (startBroadcastCookies != null) {
//            Spider.create(this).addUrl(spiderConfig.getStartBroadcastHomePageUrl()).run();
            if(isLogin()){
                return CommonUtils.webDriverHashMap.get(PageModelType.StartBroadcast);
            }
            // startBroadcastCookies 失效 先清空  cookie  后
            try {
                CommonUtils.removeCookies(PageModelType.StartBroadcast);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

            Map<String, String> homeCookies = homeProcessor.getHomeCookies();
            if (homeCookies != null) {
              // home cookie 不为空 登录开播页
                //先校验home页cookie是否有效
                if(!homeProcessor.isLogin()){
                    logger.error("home页cookie 失效");
                    //重新获取home页cookie
                    homeProcessor.getHomeCookies();
                }
                toStartBroadcastHome();
            }


        return CommonUtils.webDriverHashMap.get(PageModelType.StartBroadcast);
    }

    /**
     *   判断开播主页登录状态 是否有效 然后 判断 home页登录状态 是否有效 以此递归获取home页cookie
     * @return
     */
    public boolean isLogin() {

        Map<String, String> startBroadcastCookies =   null;
        try {
            startBroadcastCookies = CommonUtils.getStartBroadcastCookies();
        } catch (Exception e) {
             logger.error("获取开播页cookie 失败");
        }
        if(startBroadcastCookies != null){
            try {
                String result = HttpClientUtil.doGet(spiderConfig.getStartBroadcastHomePageUrl(), null, startBroadcastCookies, null);
                if(result.contains("登录") || result.contains("password")){
                    logger.error("开播主页登录状态: false");
                    return false;
                }
                logger.info("开播主页登录状态: true");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("获取开播主页cookie 登录状态异常");
                throw new RuntimeException(e);
            }
        }
        logger.error("startBroadcastCookies = null ,开播主页登录状态: false");
        return false;
    }

}
